package com.reebake.ideal.protect.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.reebake.ideal.crypto.entity.SecretKeyEntity;
import com.reebake.ideal.protect.core.ProtectParameter;
import com.reebake.ideal.protect.core.SignatureService;

public class DefaultSignatureService implements SignatureService {
    @Override
    public String sign(String data, SecretKeyEntity secretKeyEntity) {
        byte[] bytes = SecureUtil.sign(SignAlgorithm.SHA256withRSA, secretKeyEntity.getPrivateKey(), secretKeyEntity.getPublicKey()).sign(data);
        return Base64.encode(bytes);
    }

    @Override
    public boolean verify(String data, ProtectParameter protectParameter, SecretKeyEntity secretKeyEntity) {
        if(StrUtil.isBlank(protectParameter.getSignature())) {
            return false;
        }
        String resign = SecureUtil.sha256(data);
        String signature = protectParameter.getSignature();
        byte[] bytes = SecureUtil.rsa(secretKeyEntity.getPrivateKey(), secretKeyEntity.getPublicKey())
                .decrypt(signature, KeyType.PublicKey);
        String originalSignature = HexUtil.encodeHexStr(bytes);
        return originalSignature.equalsIgnoreCase(resign);
    }
}
